package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 查询行为实体
     * @param userId  用户id
     * @param equipmentId  设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //1. 判断userId是否为空
        if (userId != null){
            //  1.1不为空 使用userId查询 行为实体 (refId = 用户id  type = 用户类型  )
            Query query = Query.query(Criteria.where("refId").is(userId));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //   1.2 如果不存在基于userId创建实体数据
            if (apBehaviorEntry == null){
                ApBehaviorEntry entry = new ApBehaviorEntry();
                entry.setCreatedTime(new Date());
                entry.setRefId(userId);
                entry.setType((short) 1);
                mongoTemplate.save(entry);
                return entry;
            }
            return apBehaviorEntry;
        }

        //2. 判断设备id是否为空
        if (equipmentId != null){
            //不为空 使用设备id查询  行为实体 (refId = 设备id   type = 设备类型)
            Query query = Query.query(Criteria.where("refId").is(equipmentId));
            ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //  如果不存在基于设备id创建实体数据
            if (apBehaviorEntry == null){
                ApBehaviorEntry entry = new ApBehaviorEntry();
                entry.setCreatedTime(new Date());
                entry.setRefId(equipmentId);
                entry.setType((short) 0);
                mongoTemplate.save(entry);
                return entry;
            }
            return apBehaviorEntry;
        }

       //3. 如果userId和设备id都不存在  返回null 调用者需要判断null
        return null;
    }
}
